<script setup lang="ts">
import { reactive, ref } from 'vue'
import { updateUserPasswordAPI } from '@/api/user'
import { ElMessage } from 'element-plus'
// 表单对齐方式
const labelPosition = ref('top')
// 更新密码的接口
interface updatePasswordData {
  id: number
  oldpassword: string
  newpassword: string
  nextpassword: string
}
// 更新密码的表单
const updatePasswordData: updatePasswordData = reactive({
  id: 0,
  oldpassword: '',
  newpassword: '',
  nextpassword: ''
})
// 控制弹窗默认关闭
const state = reactive({
  changePasswordDialog: false
})

// 打开修改密码弹窗
const openChangePwd = () => {
  updatePasswordData.id = parseInt(localStorage.getItem('id'))
  state.changePasswordDialog = true
}
// 表单校验规则
const rules = reactive({
  oldpassword: [
    {
      required: true,
      message: '请输入您的旧密码',
      min: 6,
      max: 12,
      trigger: 'blur'
    }
  ],
  newpassword: [
    {
      required: true,
      message: '请输入您想修改的密码',
      min: 6,
      max: 12,
      trigger: 'blur'
    }
  ],
  nextpassword: [
    {
      required: true,
      message: '请再次确认您的新密码',
      min: 6,
      max: 12,
      trigger: 'blur'
    }
  ]
})
// 修改用户密码
const updateUserPassword = async () => {
  try {
    const res = await updateUserPasswordAPI(updatePasswordData)
    console.log(res)
    if (res.status === 200 && res.data.status === 0) {
      ElMessage.success(res.data.message)
      state.changePasswordDialog = false
      updatePasswordData.oldpassword = ''
      updatePasswordData.newpassword = ''
      updatePasswordData.nextpassword = ''
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    ElMessage.error(error)
  }
}
defineExpose({
  openChangePwd
})
</script>

<template>
  <!-- 修改密码 -->
  <el-dialog
    v-model="state.changePasswordDialog"
    title="修改密码"
    width="400px"
  >
    <el-form
      class="login-form"
      :model="updatePasswordData"
      :label-position="labelPosition"
      :rules="rules"
    >
      <el-form-item label="输入您的旧密码" prop="oldpassword">
        <el-input
          v-model="updatePasswordData.oldpassword"
          placeholder="输入您的旧密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="输入您的新密码" prop="newpassword">
        <el-input
          v-model="updatePasswordData.newpassword"
          placeholder="输入您的新密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="再次确认您的新密码" prop="nextpassword">
        <el-input
          v-model="updatePasswordData.nextpassword"
          placeholder="再次确认您的新密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <!-- 底部内容 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.changePasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="updateUserPassword()">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="less"></style>
